// 两个video
let localVideo = document.getElementById('localVideo');
let remoteVideo = document.getElementById('remoteVideo');


localVideo.addEventListener('loadedmetadata', function () {
    console.log(`Local video videoWidth: ${this.videoWidth}px,  videoHeight: ${this.videoHeight}px`)
});

remoteVideo.addEventListener('loadedmetadata', function () {
    console.log(`Remote video videoWidth: ${this.videoWidth}px,  videoHeight: ${this.videoHeight}px`)
});

let localStream;

// RTCPeerConnection
let pc1;

function close() {
    // 关闭
    if (localStream) {
        localStream.getTracks().forEach(track => {
            track.stop();
        });
    }
    if (pc1) {
        pc1.close();
        pc1 = null;
    }
}

// 打开本地视频
function start() {
    pc1 = newConn();

    const constraints = {
        audio: false,
        //audio: {
        //  deviceId: audioSource ? {exact: audioSource} : undefined,
        //},
        video: {
            width: {min: 320, ideal: 1280, max: 1920},
            height: {min: 240, ideal: 720, max: 1080},
            frameRate: {min: 5, max: 60}
        }
    };

    navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
        console.log(`getUserMedia success `, stream)

        localVideo.srcObject = stream;
        localStream = stream

        // 添加track
        stream.getTracks().forEach(
            function (track) {
                console.log(`------------ add track: `, track)
                pc1.addTrack(track, stream);
            }
        );
    })
    .catch(function (e) {
        console.log(`################getUserMedia error: `, e)
    })
}

// 创建RTCPeerConnection
function newConn() {
    // ICE
    // "stun:stun.l.google.com:19302"
    const serverConfig = {
        iceServers: [
            {
                "urls": ["turn:www.octuc.cn:3478"],
                "username": "admin",
                "credential": "147258"
            }
        ],
        iceTransportPolicy: "all"
    };

    // 创建RTCPeerConnection
    let rtcConnection = new RTCPeerConnection(serverConfig)
    // 打洞地址回调
    rtcConnection.addEventListener('icecandidate', function (e) {
        if (event.candidate == null) {
            return
        }
        // 发送给对方
        ws.send(JSON.stringify({
            type: "relayMessage",
            payload: {
                type: "candidata",
                label: event.candidate.sdpMLineIndex,
                id: event.candidate.sdpMid,
                candidate: event.candidate.candidate
            }
        }))
    })
    // 连接状态变化
    rtcConnection.addEventListener('connectionstatechange', function (e) {
        console.log(`pc1.iceConnectionState: , ${this.iceConnectionState}`)
    })
    //
    rtcConnection.addEventListener('icegatheringstatechange', function (e) {
        console.log(`gatheringStateChange, this.iceGatheringState: `, this.iceGatheringState)
        console.log(`gatheringStateChange, e: `, e)
        if (pc1.iceGatheringState !== 'complete') {
        }
    })
    rtcConnection.addEventListener('icecandidateerror', function (e) {
        console.warn(`onicecandidateerror: , e:`, e)
    })

    rtcConnection.addEventListener('track', function (e) {
        console.log(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~, `, e)
        // for (var i = 0; i < e.streams.length; i++) {
        //     console.log(e.streams[i]);
        //     if (e.track.kind == 'audio') {
        //         remoteAudio.srcObject = e.streams[i]
        //     } else if (e.track.kind == 'video') {
        //         remoteVideo.srcObject = e.streams[i];
        //         console.log('pc1 received remote stream');
        //     }
        // }
        if (e.streams.length > 0) {
            remoteVideo.srcObject = null;
            remoteVideo.srcObject = e.streams[0]
        }
    })

    rtcConnection.addEventListener('datachannel', function (e) {
        console.log(`on data channel , e: `, e)
        let receiveChannel = e.channel;
        receiveChannel.onmessage = function (e) {
            console.log(`channel on message , `, e.data, e)
        };
        receiveChannel.onopen = function () {
            console.log(`channel on open `, receiveChannel.readyState)
        };
        receiveChannel.onclose = function () {
            console.log(`channel on close `, receiveChannel.readyState)
        };
    })

    return rtcConnection;
}

// 呼叫
function call() {

    // 创建请求offer
    // 媒体方向
    // pc1.addTransceiver("video", {
    //     direction: "sendrecv"
    // })
    // pc1.addTransceiver("audio", {
    //     direction: "sendrecv"
    // })

    let offerOptions = {
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1,
        iceRestart: true
    }

    // 创建offer
    pc1.createOffer(offerOptions).then(onCreateOfferSuccess, onCreateOfferFail);
}


// 创建offer成功
function onCreateOfferSuccess(offer) {
    // 设置后, ICE开始. 收到ice data, 发送给对方
    pc1.setLocalDescription(new RTCSessionDescription(offer));

    //console.log(desc.sdp)
    // 发送offer给对方, 对方收到后回复answer. 等ice打通后, 对方会收到ontrack(取e.stream[0]播放即可)
    ws.send(JSON.stringify({
        type: "relayMessage",
        payload: {
            type: "offer",
            data: offer
        }
    }))
}

// 创建offer失败
function onCreateOfferFail(err) {
    console.error(`creater offer fail ${err}`)
}


// 收到offer请求
function onRecvOffer(obj) {
    //  设置远程
    pc1.setRemoteDescription(obj.data).then(function () {
        console.log(`--------------setRemoteDescription success`)
    })
        .catch(function () {
            console.log(`--------------setRemoteDescription fail`)
        });

    // 创建回复
    pc1.createAnswer().then(function (answerDesc) {
        let ret = pc1.setLocalDescription(answerDesc);
        console.log(`==============createAnswer: `, answerDesc);

        // 发送answer
        ws.send(JSON.stringify({
            type: "relayMessage",
            payload: {
                type: "answer",
                data: answerDesc
            }
        }))

        return ret;
    })
        .catch(function (err) {
            console.log(`--------------createAnswer fail `, err)
        });
}


let ws_onmessage = function (evt) {
    console.log("onmessage ", evt.data);

    let obj = JSON.parse(evt.data)
    if (obj.type !== "relayMessage") {
        return
    }

    obj = obj.payload

    if (obj.type === 'candidata') {
        // 收到对方的打洞ICE消息
        if (obj.candidate != null) {
            var candidate = new RTCIceCandidate({
                sdpMLineIndex: obj.label,
                candidate: obj.candidate
            });

            pc1.addIceCandidate(candidate);
        }
    } else if (obj.type === 'offer') {
        // 收到对方的请求offer
        onRecvOffer(obj);
    } else if (obj.type === "answer") {
        // 收到对方回复的answer
        pc1.setRemoteDescription(new RTCSessionDescription(obj.data))
            .then(function () {
                console.log(`-------[answer]-------setRemoteDescription success`)
            })
            .catch(function (err) {
                console.log(`-------[answer]-------setRemoteDescription fail `, err)
            });
    }
};
